package top.revery.task.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.user.BaseMyCollection;
import top.revery.task.dto.MyCollectionDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/17 11:44
 */
@Service
public class MyCollectionService {
    @Autowired
    private MyCollectionDto myCollectionDto;

    public Page<BaseMyCollection> findPage(int pageNum, int pageSize, Map map) {

        Specification<BaseMyCollection> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return myCollectionDto.findAll(specification, pageRequest);
    }

    private Specification<BaseMyCollection> createSpecification(Map map) {
        return new Specification<BaseMyCollection>() {
            @Override
            public Predicate toPredicate(Root<BaseMyCollection> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
              //企业id
                if (map.get("companyId") != null && !"".equals(map.get("companyId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("companyId"), map.get("companyId")));
                }
                //网红id
                if (map.get("userId") != null && !"".equals(map.get("userId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("userId"), map.get("userId")));
                }
                if (map.get("name") != null && !"".equals(map.get("name"))) {
                    predicate.getExpressions().add(cb.equal(root.get("name"), map.get("name")));
                }
                return predicate;
            }
        };
    }
}
